#include "GY_GroupControl.h"
#include <QDebug>

QMap<QVariant, QList<Hander>> GY_GroupControl::m_groupIdMap;

GY_GroupControl::GY_GroupControl()
{

}

/**
 * @brief addGroupMember 添加组成员
 * @param groupId 组号
 * @param pReceiver 对象
 * @param pMethodName 调用函数
 */
void GY_GroupControl::addGroupMember(const QVariant &groupId, QObject *pReceiver, const char *pMethodName)
{
    if(pReceiver==nullptr) //如果对象不存在
    {
        qDebug()<<"receiver==nullptr";
        return;
    }
    QList<Hander> &handerList = m_groupIdMap[groupId];
    Hander hander;
    hander.first = pReceiver;
    hander.second = pMethodName;
    handerList<< hander;
}

/**
 * @brief removeGroupMember 移除监听对象
 * @param pReceiver 对象
 */
void GY_GroupControl::removeGroupMember(QObject *pReceiver)
{
    QMap<QVariant,QList<Hander>>::Iterator iter = m_groupIdMap.begin();
    while(iter !=m_groupIdMap.end())
    {
        QList<Hander> &handerList = iter.value();
        for(int i=0;i<handerList.length();++i)
        {
            const Hander &hander = handerList.at(i);
            if(hander.first==pReceiver)
            {
                handerList.removeAt(i);
                break;
            }
        }
        if(handerList.length()==0)
        {
            iter = m_groupIdMap.erase(iter);
        }
        else {
            ++iter;
        }
    }
}

/**
 * @brief emitEvent 响应事件
 * @param groupId 组号
 */
void GY_GroupControl::emitEvent(const QVariant &groupId, QObject *pReceiver)
{
    if(!m_groupIdMap.contains(groupId))
    {
        qDebug()<< QString("no such groupId: %1").arg(groupId.toString());
        return;
    }
    QMap<QVariant, QList<Hander>>::iterator groupIdIter;
    for(groupIdIter=m_groupIdMap.begin();groupIdIter!=m_groupIdMap.end();++groupIdIter)
    {
        QString id = groupIdIter.key().toString();
        if(groupId==groupIdIter.key()) //如果组号相同
        {
            const QList<Hander> &handerList = m_groupIdMap[groupIdIter.key()];
            for(int i=0; i<handerList.length();i++)
            {
                const Hander &hander = handerList.at(i);
                QObject* pHanderReciver = hander.first; //对象
                if(pReceiver!=pHanderReciver)
                {
                    const char* pMethodName = hander.second; //调用函数名
                    bool ok = QMetaObject::invokeMethod(pHanderReciver,pMethodName,
                                                        Qt::AutoConnection,
                                                        QGenericReturnArgument());
                    if(!ok)
                    {
                        qDebug()<< QString("pHanderReciver Description Failed to process Event with %2").arg(pMethodName);
                    }
                }

            }
        }
    }
}
